package cn.sh.ideal.yedis.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public abstract class Serializer {
	
	public static byte[] serialize(Object object) {
		ByteArrayOutputStream byteStream = new ByteArrayOutputStream(1024);
		try  {
			if (!(object instanceof Serializable)) {
				throw new IllegalArgumentException(Serializer.class.getSimpleName() + " requires a Serializable payload " +
						"but received an object of type [" + object.getClass().getName() + "]");
			}
			ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteStream);
			objectOutputStream.writeObject(object);
			objectOutputStream.flush();
			
			return byteStream.toByteArray();
		}catch (Throwable ex) {
			throw new RuntimeException("Failed to serialize object ", ex);
		}
		
	}
	
	@SuppressWarnings("unchecked")
	public static <T> T deserialize(byte[] source) {
		ByteArrayInputStream byteStream = new ByteArrayInputStream(source);
		try {
			ObjectInputStream objectInputStream = new ObjectInputStream(byteStream);
			return (T)objectInputStream.readObject();
		}
		catch (Exception ex) {
			throw new RuntimeException("Failed to deserialize object type", ex);
		}
	}
}
